package com.java.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.java.model.Company;
import com.java.model.Department;
import com.java.model.PageBean;
import com.java.model.User;
import com.java.service.CompanyService;
import com.java.service.DepartmentService;
import com.java.service.UserService;
import com.java.util.AppConfig;
import com.java.util.PageUtil;
import com.java.util.PwdUtil;
import com.java.util.ResponseUtil;
import com.java.util.StringUtil;

@Controller
@RequestMapping("/user")
public class UserController {

	@Resource
	private UserService userService;

	@Autowired
	private DepartmentService departmentService;

	@Autowired
	private CompanyService companyService;

	@RequestMapping("/visitor")
	public String visitor(HttpServletRequest request) {
		User user = new User();
		user.setUserName("visitor");
		user.setPassword(PwdUtil.encryptMd5("123"));
		User resultUser = userService.login(user);
		HttpSession session = request.getSession();
		System.out.println("currentUser:" + resultUser.toString());
		session.setAttribute("currentUser", resultUser);
		return "redirect:/main.jsp";
	}

	@RequestMapping("/login")
	public String login(User user, HttpServletRequest request) {
		user.setPassword(PwdUtil.encryptMd5(user.getPassword()));
		User resultUser = userService.login(user);
		if (resultUser.getId() == null) {
			request.setAttribute("user", user);
			request.setAttribute("errorMsg", "用户名或密码错误！");
			return "login";
		} else {
			HttpSession session = request.getSession();
			System.out.println("currentUser:" + resultUser.toString());
			session.setAttribute("currentUser", resultUser);
			return "redirect:/main.jsp";
		}
	}

	@RequestMapping("/logout")
	public String logout(HttpSession session) {
		session.invalidate();
		return "redirect:/login.jsp";
	}

	@RequestMapping("/list")
	public ModelAndView list(@RequestParam(value = "page", required = false) String page, User s_user,
			HttpServletRequest request) {
		ModelAndView mav = new ModelAndView();
		HttpSession session = request.getSession();
		if (StringUtil.isEmpty(page)) {
			page = "1";
			session.setAttribute("s_user", s_user);
		} else {
			s_user = (User) session.getAttribute("s_user");
		}
		PageBean pageBean = new PageBean(Integer.parseInt(page), AppConfig.pageSize);
		List<User> userList = userService.find(pageBean, s_user);
		int total = userService.count(s_user);
		String pageCode = PageUtil.getPagation(request.getContextPath() + "/user/list.do", total,
				Integer.parseInt(page), AppConfig.pageSize);
		mav.addObject("pageCode", pageCode);
		mav.addObject("modeName", "用户管理");
		mav.addObject("userList", userList);
		mav.addObject("mainPage", "user/list.jsp");
		mav.setViewName("main");
		return mav;
	}

	@RequestMapping("/delete")
	public void delete(@RequestParam(value = "id") String id, HttpServletResponse response) throws Exception {
		JSONObject result = new JSONObject();
		userService.delete(Integer.parseInt(id));
		result.put("success", true);
		ResponseUtil.write(result, response);
	}

	@RequestMapping("/preSave")
	public ModelAndView preSave(@RequestParam(value = "id", required = false) String id) {
		ModelAndView mav = new ModelAndView();
		mav.addObject("mainPage", "user/save.jsp");
		mav.addObject("modeName", "用户管理");
		mav.setViewName("main");
		if (StringUtil.isNotEmpty(id)) {
			mav.addObject("actionName", "用户修改");
			User user = userService.loadById(Integer.parseInt(id));
			mav.addObject("user", user);
		} else {
			mav.addObject("actionName", "用户添加");
		}
		List<Company> companyList = companyService.find(null, null);
		mav.addObject("companyList", companyList);

		List<Department> departmentList = departmentService.find(null, null);
		mav.addObject("departmentList", departmentList);
		return mav;
	}

	@RequestMapping("/reset")
	public void reset(@RequestParam(value = "id", required = false) String id) {
		User user = userService.loadById(Integer.valueOf(id));
		user.setPassword(PwdUtil.encryptMd5("123"));
		userService.update(user);
	}

	@RequestMapping("/register")
	public ModelAndView preSaveVisitor(@RequestParam(value = "id", required = false) String id) {
		ModelAndView mav = new ModelAndView();
		mav.addObject("mainPage", "user/register.jsp");
		mav.addObject("modeName", "用户管理");
		mav.setViewName("main");
		mav.addObject("actionName", "用户添加");
		Department department = new Department();
		department.setDeptName("客户部门");
		List<Department> departmentList = departmentService.find(null, department);
		mav.addObject("departmentList", departmentList);
		return mav;
	}

	/**
	 * 若存在则返回“1”，若不存在则返回“0”
	 * 
	 * @param lastName
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/ajaxValidateUserName", method = RequestMethod.POST)
	public String validateLastName(@RequestParam(value = "userName", required = true) String userName) {
		boolean isExist = userService.existUserName(userName);
		if (!isExist) {
			return "0";
		} else {
			return "1";
		}
	}

	@RequestMapping("/save")
	public String save(User user, HttpSession session, HttpServletRequest request) {
		if (user.getId() == null) {
			user.setPassword(PwdUtil.encryptMd5(user.getPassword()));
			if (!userService.existUserName(user.getUserName())) {
				userService.add(user);
			} else {
				return "redirect:/user/preSave.do";
			}
		} else {
			User cuser = (User) session.getAttribute("currentUser");
			if (!"管理员".equals(cuser.getRoleName())) {
				User fuser = userService.loadById(user.getId());
				if (!fuser.getPassword().equals(user.getPassword())) {
					user.setPassword(PwdUtil.encryptMd5(user.getPassword()));
				}
				userService.update(user);
				return "main";
			}
			userService.update(user);

		}
		return "redirect:/user/list.do";
	}
}
